import axios from '../../axios';
import Api from '../../constants/Api';

export default {
  state: {
    tagsList: localStorage.getItem('tagList') ? JSON.parse(localStorage.getItem('tagList')) : [],
    envTree: localStorage.getItem('envNav') ? JSON.parse(window.localStorage.getItem('envNav')) : [],
    reqTree:  [],
  },
  getters: {
    includePageNames(state) {
      return state.tagsList.map((item) => item.name);
    },
  },
  mutations: {
    // 设置标签
    setTags(state, route = {}) {
      const isExist = state.tagsList.some((item) => item.path === route.fullPath);
      !isExist && state.tagsList.push({
        title: route.params.id ? `${route.params.label}` : route.meta.title,
        path: route.fullPath,
        name: route.name,
      });
    },
    // 删除单个标签
    delTags(state, data = {}) {
      const { index } = data;
      if (state.tagsList.length === 1 && state.tagsList[0].path === '/index') {
        return;
      }
      const delItem = state.tagsList.splice(index, 1)[0];
      const item = state.tagsList[index] ? state.tagsList[index] : state.tagsList[index - 1];
      if (data.callback && typeof data.callback === 'function') {
        data.callback({
          delItem,
          item,
        });
      }
    },
    // 清空所有标签
    clearAllTags(state) {
      state.tagsList = [];
    },
  },
  actions: {
    getEnvTree({ state }, that) {
      let _data = {
        id: that.treeForm.id,
        sysHead: {
          serviceCode: 'MbsdAccount',
          messageType: '',
          messageCode: ''
        },
        appHead: {
          totalNum: '-1',
          currentPage: ''
        },
        body: {}
      };
      axios({
        method: 'post',
        url: Api.getEnvTree,
        data: _data
      })
        .then((res) => {
          state.envTree = res.data;
          return res;
        })
        .catch((err) => err);
    },
    getReqTree({ state }, that) {
      let _data = {
        id: that.treeForm.id,
        sysHead: {
          serviceCode: 'MbsdAccount',
          messageType: '',
          messageCode: ''
        },
        appHead: {},
        body: {}
      };
      axios({
        method: 'post',
        url: Api.getReqTree,
        data: _data
      })
        .then((res) => {
          state.reqTree = res.data;
          return res;
        })
        .catch((err) => err);
    },
  },
};
